<template>
  <el-dialog
      title="修改密码"
      :visible.sync="modelValue"
      width="400px"
      :before-close="handleClose"
  >
    <el-form
        :model="changePwdForm"
        :rules="changePwdRules"
        ref="changePwdFormRef"
        label-width="100px"
    >
      <el-form-item label="原密码" prop="oldPassword">
        <el-input
            v-model="changePwdForm.oldPassword"
            type="password"
            placeholder="请输入原密码"
            autocomplete="off"
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="changePwdForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            autocomplete="off"
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="changePwdForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            autocomplete="off"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="submitChange">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,  // 控制弹窗显示
  savedPassword: String // 用于校验原密码
})

const emit = defineEmits(['update:modelValue', 'password-changed'])

const changePwdFormRef = ref(null)

const changePwdForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const changePwdRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度 6~20 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== changePwdForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 关闭弹窗时清空表单
const clearForm = () => {
  changePwdForm.oldPassword = ''
  changePwdForm.newPassword = ''
  changePwdForm.confirmPassword = ''
}

const handleCancel = () => {
  emit('update:modelValue', false)
  clearForm()
}

const handleClose = () => {
  emit('update:modelValue', false)
  clearForm()
}

// 提交修改
const submitChange = () => {
  changePwdFormRef.value.validate((valid) => {
    if (!valid) return
    // 校验原密码
    if (changePwdForm.oldPassword !== props.savedPassword) {
      ElMessage.error('原密码错误')
      return
    }
    // 触发事件，告诉父组件密码修改成功，并传递新密码
    emit('password-changed', changePwdForm.newPassword)
    ElMessage.success('密码修改成功！')
    handleCancel()
  })
}
</script>

<style scoped>
.el-dialog {
  --el-dialog-zindex: 2000;
}
</style>
